package com.hy.convenient.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 用于登录认证相关数据库
 */
@Configuration
@MapperScan(basePackages = "com.hy.convenient.api.dao" , sqlSessionFactoryRef = "apiSqlSessionFactory")
public class ApiDataSourceConfiguration {
    @Bean("dataSourceapi")
    @ConfigurationProperties(prefix = "spring.datasourceapi")
    public DataSource datasource2() {
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource;
    }

    /**
     * SqlSession对象创建
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "apiSqlSessionFactory")
    public SqlSessionFactory DB1Factory(@Qualifier("dataSourceapi") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        //指定起别名的包, 这里注意, 设置该参数时打成jar启动会找不到该包下的类,目前未找到解决方案
        bean.setTypeAliasesPackage("com.hy.convenient.api.pojo");
        bean.setDataSource(dataSource);
        //指定该SqlSession对应的mapper.xml文件位置
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/api/*.xml"));
        return bean.getObject();
    }
}
